package com.kbt.activity;

import android.content.Intent;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Paint;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.*;
import com.android.volley.Request;
import com.kbt.adapter.TeMaiAndKaiQiangAdapter;
import com.kbt.base.BaseApplication;
import com.kbt.commont.Constants;
import com.kbt.model.data.*;
import com.kbt.net.RequestManager;
import com.kbt.util.utils.ImageManager;
import com.kbt.util.utils.LoadingDialog;
import com.kbt.util.utils.NoScrollGridView;
import com.kbt.util.utils.Utils;

import javax.sql.RowSetListener;
import java.io.Serializable;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

public class TeMaiKaiQiangActivity extends Activity implements RequestManager.ResponseInterface{
	private NoScrollGridView gv;
	private ImageView title_image;
	private List<TeMaiAndKaiQiangBean> teMaiAndKaiQiangBeans = new ArrayList<TeMaiAndKaiQiangBean>();
	private TeMaiAndKaiQiangListBean teMaiAndKaiQiangListBean;
	private TeMaiAndKaiQiangAdapter adapter;
	private String active_id;
	private String active_desc;
	private String active_icon;
	private RequestManager mRequestManager;
	private Map<String,Object> map=null;
	private LoadingDialog mProgress;
	private TextView shop_shuoMing;
	public  static  String tag ;
	private TextView teMai_time;
	private String startTime;
	private String endTime;
	private String title;

	private long hours;
	private long minutes;
	private long seconds;
	private long diff;
	private long days;
	private long haomiao ;
	private TeMaiAndKQHandler teMaiKQHandler;
	private List<Goods> goodss = new ArrayList<Goods>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.te_mai_and_kai_qiang);

		this.getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title_return_btn);

		//设置返回按钮事件,关闭当前Activity，返回数据
		ImageView returnImg = (ImageView) findViewById(R.id.return_btn);
		returnImg.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				BaseApplication.getInstance().removeActivity(TeMaiKaiQiangActivity.this);
				finish();
			}
		});
		BaseApplication.getInstance().addActivity(TeMaiKaiQiangActivity.this);
		BaseApplication.getInstance().addActivitytwo(TeMaiKaiQiangActivity.this);
		TextView appTitleView = (TextView) findViewById(R.id.center_title);
		//初始化ImageLoader
		ImageManager.init();
		initData();
		init();
		setListener();
		httpGetData();
		//设置标题
		appTitleView.setText(title);
	}
	//初始化组件
	private void init(){
		teMai_time = (TextView) findViewById(R.id.teMai_time);
		if(teMaiKQHandler==null) {
			teMaiKQHandler = new TeMaiAndKQHandler();
		}
//		if(tag!=null&&tag.equals("kaiQiang")) {
//			goodss.add(new Goods(getTime(getNewTime(), startTime+":000")));
//		}else{
//			goodss.add(new Goods(getTime(getNewTime(),endTime+":000")));
//		}
		if(getTimeCha(startTime)) {
			goodss.add(new Goods(getTime(getNewTime(), startTime+":000")));
			tag = "kaiQiang";
		}else{
			goodss.add(new Goods(getTime(getNewTime(),endTime+":000")));
		}
		teMaiKQHandler.sendEmptyMessage(1);
		title_image = (ImageView) findViewById(R.id.title_image);

		int screenWidth = getWindowManager().getDefaultDisplay().getWidth();
		ViewGroup.LayoutParams lp = title_image.getLayoutParams();
		lp.width = screenWidth;

		String[] url_params = active_icon.split("&");

		int imageWidth = 0;
		int imageHeight = 0;
		if(url_params.length == 3){
			imageWidth = Integer.parseInt(url_params[1].split("=")[1]);
			imageHeight = Integer.parseInt(url_params[2].split("=")[1]);
		}
		if(imageWidth>0 && imageHeight>0){
			lp.height = new Float(imageHeight*screenWidth/imageWidth).intValue();
		}else{
			lp.height = ViewGroup.LayoutParams.MATCH_PARENT;
		}
		title_image.setLayoutParams(lp);
		title_image.setMaxWidth(screenWidth);
		title_image.setMaxHeight(screenWidth *10);
		ImageManager.imageLoader.displayImage(Constants.ServiceInterFace.imageURL + active_icon, title_image, ImageManager.getOptions(
				R.drawable.loadings, R.drawable.loadings));
		shop_shuoMing = (TextView) findViewById(R.id.shop_shuoMing);
		shop_shuoMing.setText(active_desc);
		gv = (NoScrollGridView) findViewById(R.id.teMai_GridView);
		//设置GridView的行数
		gv.setNumColumns(2);
		adapter = new TeMaiAndKaiQiangAdapter(TeMaiKaiQiangActivity.this,teMaiAndKaiQiangBeans);
		gv.setAdapter(adapter);
	}
	//初始化监听
	private void setListener(){

	}

	private void initData(){
		Intent intent = getIntent();
		active_id = intent.getStringExtra("active_id");
		active_desc = intent.getStringExtra("active_desc");
		active_icon = intent.getStringExtra("active_icon");
		tag = intent.getStringExtra("tag");
		startTime = intent.getStringExtra("startTime");
		endTime = intent.getStringExtra("endTime");
		title = intent.getStringExtra("title");
		mRequestManager = new RequestManager();
		mRequestManager.setResponseListener(this);
		map = new HashMap<String, Object>();
	}
	//请求数据
	private void httpGetData(){
		showProgress();
		if(Utils.isNetworkAvailable(TeMaiKaiQiangActivity.this)) {
			mRequestManager.requestGet(Request.Method.GET, Constants.ServiceInterFace.selectActiveURL+"&active_id="+active_id, Constants.RequestTag.selectActiveTag, map, TeMaiAndKaiQiangListBean.class);
		}else {
			stopProgress();
			Toast.makeText(TeMaiKaiQiangActivity.this, R.string.Wangluo, Toast.LENGTH_SHORT).show();
		}
	}

	@Override
	public <T> void successResponse(T parsedGSON, int tag) {
		stopProgress();
		if (tag == Constants.RequestTag.selectActiveTag) {
			/** 判断返回值不为空 **/
			if (parsedGSON != null) {
				teMaiAndKaiQiangListBean = (TeMaiAndKaiQiangListBean) parsedGSON;
				if (teMaiAndKaiQiangListBean.getResult().equals("success")) {
					if(teMaiAndKaiQiangListBean.getData().size()>0){
						if(teMaiAndKaiQiangListBean.getData().size()>1) {
							teMaiAndKaiQiangBeans = teMaiAndKaiQiangListBean.getData();
							adapter.setList(teMaiAndKaiQiangBeans);
							adapter.notifyDataSetChanged();
						}else{
							Intent intent = new Intent(TeMaiKaiQiangActivity.this,GoodInfoActivity.class);
							intent.putExtra("shopId",teMaiAndKaiQiangListBean.getData().get(0).getGoods_id());
							startActivity(intent);
							finish();
						}
					}
				}else{
					Toast.makeText(TeMaiKaiQiangActivity.this,teMaiAndKaiQiangListBean.getMsg(),Toast.LENGTH_SHORT).show();
				}
			}
		}
	}

	@Override
	public void errorResonse(String retmeg, int tag) {
		stopProgress();
		Toast.makeText(TeMaiKaiQiangActivity.this,R.string.noWangluo,Toast.LENGTH_SHORT).show();
	}
	/**
	 * progressDialog的展示
	 */
	public void showProgress() {
		if (mProgress == null) {
			mProgress = new LoadingDialog(TeMaiKaiQiangActivity.this,"");
			mProgress.setCancelable(true);
			mProgress.show();

		} else {
			if (mProgress.isShowing()) {
				stopProgress();
			} else {
				mProgress.show();
			}
		}
	}


	/**
	 * progressDialog的消失
	 */
	public void stopProgress() {
		if (mProgress != null) {
			mProgress.dismiss();
			mProgress = null;
		}
	}

	private class TeMaiAndKQHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
				case 1:
					boolean isNeedCountTime = false;
					//①：其实在这块需要精确计算当前时间
					for (int index = 0; index < goodss.size(); index++) {
						Goods goods = goodss.get(index);
						long time = goods.getTime();
						if (time > 100) {//判断是否还有条目能够倒计时，如果能够倒计时的话，延迟一秒，让它接着倒计时
							isNeedCountTime = true;
							goods.setTime(time - 100);
							days = goods.getTime() / (1000 * 60 * 60 * 24);
							hours = (goods.getTime()-days*(1000 * 60 * 60 * 24))/(1000* 60 * 60);
							minutes = (goods.getTime()-days*(1000 * 60 * 60 * 24)-hours*(1000* 60 * 60))/(1000* 60);
							seconds = (goods.getTime()-days*(1000 * 60 * 60 * 24)-hours*(1000* 60 * 60)-minutes*(1000* 60))/(1000);
							haomiao =  (goods.getTime()-days*(1000 * 60 * 60 * 24)-hours*(1000* 60 * 60)-minutes*(1000* 60)-seconds*1000)/(100);
							if(getTimeCha(startTime)) {
								teMai_time.setText(  days + "天" + hours + ":" + minutes + ":" + seconds+"后开抢");
							}else {
								teMai_time.setText("剩" + days + "天" + hours + ":" + minutes + ":" + seconds+":"+haomiao);
							}
						} else {
							goods.setTime(0);
							days = goods.getTime() / (1000 * 60 * 60 * 24);
							hours = (goods.getTime()-days*(1000 * 60 * 60 * 24))/(1000* 60 * 60);
							minutes = (goods.getTime()-days*(1000 * 60 * 60 * 24)-hours*(1000* 60 * 60))/(1000* 60);
							seconds = (goods.getTime()-days*(1000 * 60 * 60 * 24)-hours*(1000* 60 * 60)-minutes*(1000* 60)) / (1000);
							haomiao =  (goods.getTime()-days*(1000 * 60 * 60 * 24)-hours*(1000* 60 * 60)-minutes*(1000* 60)-seconds*1000)/(100);
							if(getTimeCha(startTime)) {
								teMai_time.setText("剩" + days + "天" + hours + ":" + minutes + ":" + seconds);
							}else{
								teMai_time.setText("剩" + days + "天" + hours + ":" + minutes + ":" + seconds + ":" + haomiao);
							}
						}
					}
					if (isNeedCountTime) {
						teMaiKQHandler.sendEmptyMessageDelayed(1,100);
					}
					break;
			}
		}
	}

	//获取当前时间
	private String getNewTime(){
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
		return df.format(new Date());
	}

	/**
	 * 得到时间差
	 */
	private  Long getTime(String time,String time2){

		DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
		try
		{
			Date d1 = df.parse(time2);
			Date d2 = df.parse(time);
			diff = d1.getTime() - d2.getTime();//这样得到的差值是微秒级别
			return diff;
		}
		catch (Exception e)
		{
		}
		return null;
	}

	/**
	 * 判断开抢还是特卖
	 */
	private  boolean getTimeCha(String time2){

		DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try
		{
			Date d1 = df.parse(time2);
			Date d2 = df.parse(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
			long diff = d1.getTime() - d2.getTime();
			if(diff>0){
				return true;//开抢
			}else{
				return false;
			}

		}
		catch (Exception e)
		{
		}
		return false;
	}



}
